<template>
  <div>
    <BasicTable
      @register="registerTable"
      title="模板库单元分类管理"
      :indentSize="30"
      :pagination="false"
      @fetch-success="onFetchSuccess"
      :scroll="{ x: false, y: 'calc(100vh - 300px)' }"
    >
      <template #toolbar>
        <a-button type="primary" @click="onAddUnitCategoryButtonClick">新增</a-button>
      </template>
      <template #uctype="{ column, record }">
        {{
          unitTypeOption.filter((item) => item.value == record.uctype).length > 0
            ? unitTypeOption.filter((item) => item.value == record.uctype)[0].label
            : record.uctype
        }}
      </template>
      <template #isconstruction="{ column, record }">
        <template v-if="record.isconstruction">
          <Tag :color="'green'">是</Tag>
        </template>
        <template v-else>
          <Tag :color="'red'">否</Tag>
        </template>
      </template>
      <template #hdbcd="{ column, record }">
        {{ returnDangerDbLabel(record.hdbcd) }}
      </template>
      <template #action="{ column, record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              color: 'success',
              label: '设置关联危险源',
              onClick: onSetHasHazard.bind(null, record),
            },
            {
              icon: 'clarity:note-edit-line',
              label: '编辑',
              onClick: onEditUnitCategoryButtonClick.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              label: '删除',
              popConfirm: {
                title: '是否确认删除',
                placement: 'left',
                confirm: onDeleteUnitCategoryButtonClick.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <AddOrUpdateUnitCategory
      @register="registerAddOrUpdateUnitCategoryModal"
      @success="afterSuccess"
    />
    <SetHasHazardList @register="registerSetHasHazardModal" @success="afterSuccess" />
  </div>
</template>

<script lang="ts">
  import { defineComponent, onMounted, ref, nextTick } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  import { Tag } from 'ant-design-vue';
  import { useModal } from '/@/components/Modal';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { queryUnitCategory, deleteUnitCategory } from '/@/api/ehs/unitCategory';
  import { TplUnitCategoryTreeTableItemDto } from '/@/api/ehs/model/unitCategoryModel';
  import { unitCategoryTableColumns } from './unitCategory.data';
  import AddOrUpdateUnitCategory from './AddOrUpdateUnitCategory.vue';
  import SetHasHazardList from './SetHasHazardList.vue';
  import { queryEnumOptions } from '/@/api/platform/enum';
  import { queryDangerDb } from '/@/api/ehs/templateHazard';
  export default defineComponent({
    name: 'unitCategoryIndex',
    components: { BasicTable, TableAction, Tag, AddOrUpdateUnitCategory, SetHasHazardList },
    setup() {
      const unitTypeOption = ref([]);
      const dangerDbOption = ref([]);
      const [registerAddOrUpdateUnitCategoryModal, { openModal: openAddOrUpdateUnitCategory }] =
        useModal();
      const [registerSetHasHazardModal, { openModal: openSetHasHazardModal }] = useModal();
      const [registerTable, { reload, expandAll }] = useTable({
        api: queryUnitCategory,
        columns: unitCategoryTableColumns,
        canResize: true,
        striped: true,
        showTableSetting: true,
        showIndexColumn: true,
        isTreeTable: true,
        bordered: true,
        ellipsis: true,
        indexColumnProps: {
          width: 50,
        },
        actionColumn: {
          width: 200,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
      });
      /**
       * 弹窗确认操作之后刷新页面
       */
      function afterSuccess() {
        reload();
      }
      /**
       * 打开新增窗口
       */

      function onAddUnitCategoryButtonClick() {
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '模板库单元分类管理',
          operateType: OperationTypeEnum.ADD,
        };
        openAddOrUpdateUnitCategory(true, propsData);
      }
      /**
       * 打开编辑窗口
       * @param record
       */
      function onEditUnitCategoryButtonClick(record: TplUnitCategoryTreeTableItemDto) {
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '模板库单元分类管理',
          operateType: OperationTypeEnum.EDIT,
          dataId: record.uccd,
        };
        openAddOrUpdateUnitCategory(true, propsData);
      }

      function onSetHasHazard(record: TplUnitCategoryTreeTableItemDto) {
        if (!record.hdbcd) {
          return createMessage.error(
            '当前分类没有使用的导则库,请先给该分类设置导则库才能关联存在的危险源。',
          );
        }
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '模板库单元分类管理',
          operateString: '设置关联危险源清单',
          dataId: record.uccd,
          hdbcd: record.hdbcd,
        };
        openSetHasHazardModal(true, propsData);
      }

      /**
       * 删除
       * @param record
       */
      function onDeleteUnitCategoryButtonClick(record: TplUnitCategoryTreeTableItemDto) {
        deleteUnitCategory(record.uccd)
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            if (res == undefined && (res == null || Object.keys(res).length == 0)) {
              createMessage.success('删除成功。', 2);
              afterSuccess();
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
          });
      }
      /**
       *
       * @description 返回导则库名称
       */
      function returnDangerDbLabel(code) {
        return dangerDbOption.value.filter((item) => item.hdbcd == code).length > 0
          ? dangerDbOption.value.filter((item) => item.hdbcd == code)[0].hdbnm
          : code;
      }

      /**
       * 接口请求成功后触发：展开所有列表项
       */
      function onFetchSuccess() {
        nextTick(expandAll);
      }

      onMounted(() => {
        //  获取枚举类
        queryEnumOptions('EhsUnitTypeEnum')
          .then((res) => {
            // console.log('option res', res);
            if (res != undefined && res != null && res.length > 0x0) {
              unitTypeOption.value = res[0].options.map((option) => {
                return {
                  value: Number(option.key),
                  label: option.value,
                };
              });
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
          });
        queryDangerDb({ keytype: 0 }).then((res) => {
          dangerDbOption.value = res;
        });
      });
      return {
        unitTypeOption,
        registerAddOrUpdateUnitCategoryModal,
        registerTable,
        registerSetHasHazardModal,
        afterSuccess,
        onAddUnitCategoryButtonClick,
        onEditUnitCategoryButtonClick,
        onDeleteUnitCategoryButtonClick,
        onSetHasHazard,
        returnDangerDbLabel,
        onFetchSuccess,
      };
    },
  });
</script>

<style scoped></style>
